/**
 * 
 */
package fhq.hcmute.edu.vn.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import fhq.hcmute.edu.vn.activities.R;
import fhq.hcmute.edu.vn.activities.ScannerActivity;
import fhq.hcmute.edu.vn.message.MessageFactory;
import fhq.hcmute.edu.vn.message.MyMessage;
import fhq.hcmute.edu.vn.network.SendAndReceive;
import fhq.hcmute.edu.vn.util.AndroidBitmapUtil;
import fhq.hcmute.edu.vn.util.HandlerRequestUtil;

/**
 * @author Hien Nguyen Nov 16, 2012
 */
public class ImageAdapter {
	private HashMap<Integer, MyBitmap> bitmaps;
	private LinearLayout listImage;
	private LayoutInflater inflater;
	private ImageView frameView;
	private Activity activity;
	private Handler handler;
	private View curentView;

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public ImageAdapter(Activity activity, ImageView frameView) {
		this.bitmaps = new HashMap<Integer, MyBitmap>();
		listImage = (LinearLayout) activity.findViewById(R.id.listImage);
		inflater = activity.getLayoutInflater();
		this.frameView = frameView;
		this.activity = activity;
	}

	private void init() {
		for (int i = 0; i < listImage.getChildCount(); i++) {
			View v = listImage.getChildAt(i);
			MyBitmap bitmap = bitmaps.get(i);
			v.setSelected(bitmap.isSelected());
		}
	}

	public void show(int id) {
		int index = id;
		setItemSelected(index);
		notifyDataSetChanged();
		String path = bitmaps.get(index).getPath();
		File file = new File(path);
		Bitmap bm = AndroidBitmapUtil.decodeSampledBitmapFromUri(path,
				640, 480);
		frameView.setImageBitmap(bm);
		ScannerActivity.currentBitmap = bm;
		MyBitmap bitmap = bitmaps.get(index);
		if (bitmap.isUploaded()) {
			MyMessage message =
					MessageFactory.createReviewImageMessage(index);
			excuteCommand(message);
		} else {
			try {
				byte[] bitmapByteArray =
						IOUtils.toByteArray(new FileInputStream(file));
				post(bitmapByteArray, index);
				bitmaps.get(index).setUploaded(true);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bitmap.setUploaded(true);
		}
	}

	private View.OnClickListener clickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			setCurentView(v);
			if (!v.isSelected()) {
				show(v.getId());
			}
		}
	};

	private void post(byte[] byteArray, int id) {
		MyMessage message;
		message = MessageFactory
				.createPostImageMessage(id, byteArray);
		excuteCommand(message);
	}

	private void excuteCommand(MyMessage message) {
		SendAndReceive fromServerTask =
				new SendAndReceive(activity,
						HandlerRequestUtil.TAKE_PICTURE_REQUEST, handler);
		fromServerTask.execute(message);
	}

	private void initImageView(String path) {
		Bitmap bm =
				AndroidBitmapUtil.decodeSampledBitmapFromUri(path, 320, 240);
		ImageView image = (ImageView)
				inflater.inflate(R.layout.list_image_item, null);
		image.setOnClickListener(clickListener);
		activity.registerForContextMenu(image);
		image.setId(listImage.getChildCount());
		image.setImageBitmap(bm);
		image.setSelected(false);
		image.setLayoutParams(new LayoutParams(dp2px(160), dp2px(140)));
		listImage.addView(image);
	}

	private int dp2px(int dp) {
		float density = activity.getResources().getDisplayMetrics().density;
		int px = (int) (dp * density);
		return px;
	}

	public void add(MyBitmap bitmap) {
		int id = bitmaps.size();
		bitmaps.put(id, bitmap);
		initImageView(bitmap.getPath());
	}

	public void deleteAllImage() {
		for (int i = 0; i < bitmaps.size(); i++) {
			String path = bitmaps.get(i).getPath();
			File file = new File(path);
			if (file.exists()) {
				file.delete();
			}
		}
	}

	public void remove(int index) {
		String path = bitmaps.get(index).getPath();
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
		bitmaps.remove(index);
		View v = listImage.findViewById(index);
		listImage.removeView(v);
		MyMessage message = MessageFactory.createRemovewImageMessage(index);
		excuteCommand(message);
	}

	public void removeAll() {
		deleteAllImage();
		bitmaps = new HashMap<Integer, MyBitmap>();
		listImage.removeAllViews();
		MyMessage message = MessageFactory.createRemovewAllImageMessage();
		excuteCommand(message);
	}

	public void setItemSelected(int index) {
		for (int i = 0; i < bitmaps.size(); i++) {
			if (i == index) {
				bitmaps.get(i).setSelected(true);
			} else {
				bitmaps.get(i).setSelected(false);
			}
		}
	}

	public void notifyDataSetChanged() {
		init();
	}

	public View getCurentView() {
		return curentView;
	}

	public void setCurentView(View curentView) {
		this.curentView = curentView;
	}
}
